package com.atguigu.chapter07;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/19 10:10
 */
public class Flink12_Sideout_2 {
    public static void main(String[] args) {
        OutputTag<WaterSensor> tag = new OutputTag<WaterSensor>("alert"){} ;
    
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // spit
        // 单独把超过20的水位的数据放入到一个单独的流中, 其他的数据还在主流中
        SingleOutputStreamOperator<String> main = env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .process(new ProcessFunction<WaterSensor, String>() {
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    if (value.getVc() < 20) {
                        out.collect(value + " 正常数据...");
                    } else {
                        ctx.output(tag, value);
                    }
                }
            });
        main.print("正常流");
        main.getSideOutput(tag).print("预警流");
    
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
两个用法:
   1. 放在窗口后面, 承载窗口关闭之后真正迟到的数据
   2. 对流进行切分
        如果获取到侧输出流: 需要在process中, context

 */
